<template>
    <el-card class="border-0">
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="24">
                <el-col :span="5" :offset="0">
                    <el-form-item label="标题">
                        <el-input size="small" v-model="searchForm.title" placeholder="文章标题" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="时间">
                        <div class="flex flex-row">
                            <el-date-picker style="width: 150px;" size="small"" value-format=" YYYY-MM-DDTHH:mm:ss"
                                v-model="searchForm.startTime" type="datetime" placeholder="开始时间" />
                            -<el-date-picker style="width: 150px;" size="small" value-format="YYYY-MM-DDTHH:mm:ss"
                                v-model="searchForm.endTime" type="datetime" placeholder="结束时间" />
                        </div>

                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <div class="flex items-center justify-end">
                        <el-button size="small" type="primary" @click="getData(1)">搜索</el-button>
                        <el-button size="small" @click="resetSearchForm">重置</el-button>
                        <el-button size="small" type="primary" @click="handleCreate">新增</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="5" :offset="0">
                    <el-form-item label="作者">
                        <el-input size="small" v-model="searchForm.authorName" placeholder="作者" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7" :offset="0">
                    <el-form-item label="文章状态">
                        <el-select size="small" v-model="searchForm.status" clearable>
                            <el-option label="全部" value=""></el-option>
                            <el-option label="已上架" value="UP"></el-option>
                            <el-option label="已下架" value="DOWN"></el-option>
                            <el-option label="待上架" value="PRE_UP"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

        </el-form>

        <!-- 表格数据 -->
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column label="标题" align="center">
                <template #default="{ row }">
                    {{ row.title }}
                </template>
            </el-table-column>

            <el-table-column label="作者" align="center">
                <template #default="{ row }">
                    {{ row.authorName }}
                </template>
            </el-table-column>

            <el-table-column label="状态" align="center">
                <template #default="{ row }">
                    {{ row.statusName }}
                </template>
            </el-table-column>

            <el-table-column label="权重" align="center">
                <template #default="{ row }">
                    {{ row.ranking }}
                </template>
            </el-table-column>
            <el-table-column label="点击量" align="center">
                <template #default="{ row }">
                    {{ row.pv }}
                </template>
            </el-table-column>

            <el-table-column label="创建时间" width="150" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.createTime) }}
                </template>
            </el-table-column>

            <el-table-column label="更新时间" width="150" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.updateTime) }}
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button @click="handleEdit(scope.row)" type="primary" size="small" text>编辑</el-button>
                    <el-button @click="handleDetail(scope.row)" type="primary" size="small" text>详情</el-button>
                    <el-popconfirm title="确定删除文章吗?" @confirm="handleDelete(scope.row)">
                        <template #reference>
                            <el-button type="primary" size="small" text>删除</el-button>
                        </template>
                    </el-popconfirm>

                </template>

            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="parseInt(searchForm.total)"
                :current-page="searchForm.pageNo" :page-size="searchForm.pageSize" @current-change="getData" />
        </div>
    </el-card>

    <FormDrawer size="60%" ref="formDrawerRef" :showSubBtn="showSubBtn" :title="drawerTitle" @submit="handleSubmit"
        @isClosed="isClosed">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">

            <el-form-item label="作者名称" prop="authorName">
                <el-input :disabled="!showSubBtn" v-model="form.authorName" placeholder="作者名称"></el-input>
            </el-form-item>
            <el-form-item label="文章标题" prop="title">
                <el-input :disabled="!showSubBtn" v-model="form.title" placeholder="文章标题"></el-input>
            </el-form-item>
            <el-form-item label="文章权重" prop="ranking">
                <el-input-number :disabled="!showSubBtn" v-model="form.ranking" :min="1" />
            </el-form-item>
            <el-form-item label="文章状态" prop="status">
                <el-select :disabled="!showSubBtn" v-model="form.status" placeholder="文章状态">
                    <el-option v-for="item in articleStatusList" :key="item.code" :label="item.description"
                        :value="item.code">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="发布时间" prop="upTime">
                <el-date-picker :disabled="!showSubBtn" v-model="form.upTime" type="datetime" placeholder="发布时间" />
            </el-form-item>
            <el-form-item label="文章图片" prop="image">
                <el-upload :disabled="!showSubBtn" list-type="picture-card" action='' accept=".jpg, .png" :limit="1"
                    :auto-upload="false" :file-list="fileList" :on-change="getFile" :on-remove="handleUploadRemove"
                    :on-exceed="onExceed_file">
                    <!-- <el-button v-if="showSubBtn" size="small" type="primary">选择图片上传</el-button>
                    <div class="ml-2 ">(只能上传一张jpg/png文件)</div> -->
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>

            </el-form-item>
            <el-tabs v-model="activeName">
                <el-tab-pane label="中文" name="first">
                    <el-form-item label="文章内容" prop="content">
                        <Editor v-if="showEditor" :contentHtml="form.content" @update:contentHtml="handleContentChange" ref="editorRef" />
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="英文" name="second">
                    <el-form-item label="文章内容" prop="content">
                        <Editor v-if="showEditor" :contentHtml="form.EnContent" ref="editorRef_en" />
                    </el-form-item>
                </el-tab-pane>
            </el-tabs>
        </el-form>
    </FormDrawer>
</template>

<script setup>
import { reactive, onMounted, ref, computed } from 'vue'
import { articleQueryPage, articleAddOrUpdate, article_delete_api, article_detail_api } from '~/api/official_article_api';
import { transferSex, transferPcState, dateFormatter } from '~/utils/common.js'
import FormDrawer from "~/components/FormDrawer.vue";
import Editor from "~/components/editor.vue";
import { toast, toastWarn } from "~/composables/util"


// -------------------- data --------------------

//tab页
const activeName = ref('first')

const searchFormInitObject = {
    id: '',
    pageNo: 1,
    pageSize: 10,
    title: '',
    startTime: '',
    endTime: '',
    status: '',
    authorName: '',
    total: 1,
}
const searchForm = reactive(searchFormInitObject)

const tableData = ref([])
const formDrawerRef = ref(null)
const formRef = ref(null)
// 编辑id
const showSubBtn = ref('1')
const editId = ref('')
const drawerTitle = ref('')

const form_init = {
    id: '',
    authorName: '',
    title: '',
    content: '',
    EnContent: '',
    status: 'UP',
    upTime: '',
    ranking: 1,
    image: '',
    officialArticleItemList: [
        {
            id: '',
            articleId: '',
            lang: 'zh',
            content: ''
        },
        {
            id: '',
            articleId: '',
            lang: 'en',
            content: ''
        }
    ]
}
// 新增更新表单
const form = reactive(form_init)
// 富文本
const editorRef = ref(null)
const editorRef_en = ref(null)
// 上传文章图片data
const proofImage = ref('')
const fileList = ref([])
const showEditor = ref(false)
const articleDetail = ref(null)

//执行表单校验
const rules = {
    authorName: [
        { required: true, message: '作者不能为空', trigger: 'change' }
    ],
    title: [
        { required: true, message: '文章标题不能为空', trigger: 'change' }
    ],
    status: [
        { required: true, message: '文字状态不能为空', trigger: 'change' }
    ],
    upTime: [
        { required: true, message: '上架时间不能为空', trigger: 'change' }
    ],
    image: [
        { required: true, message: '文章图片', trigger: 'change' }
    ],
    content: [
        { required: true, message: '文字内容不能为空', trigger: 'change' }
    ],
}
const articleStatusList = [
    {
        code: 'UP',
        description: '已上架'
    },
    {
        code: 'DOWN',
        description: '已下架'
    },
    {
        code: 'PRE_UP',
        description: '待上架'
    }
]

// -------------------- function --------------------

function handleContentChange(content) {
      this.form.content = content;
      // 手动触发校验
      this.$refs.formRef.validateField('content');
    }

//重置searchForm
function resetSearchForm() {
    for (let key in searchFormInitObject) {
        searchForm[key] = searchFormInitObject.key;
    }

}

// 获取列表
const getData = (p) => {
    if (typeof p == "number") {
        searchForm.pageNo = p
    }
    articleQueryPage(searchForm).then(res => {
        console.log('文章list：', res.records)

        tableData.value = res.records
        searchForm.total = res.total
    })
}
// 重置表单
function resetForm(row = false) {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

// 新增按钮点击事件
const handleCreate = () => {
    //修改标记置为0
    editId.value = ''
    drawerTitle.value = '新增'
    fileList.value = []
    resetForm({
        id: '',
        authorName: '',
        title: '',
        content: '',
        EnContent: '',
        status: 'UP',
        upTime: '',
        ranking: 1,
        image: '',
        officialArticleItemList: [
            {
                id: '',
                articleId: '',
                lang: 'zh',
                content: ''
            },
            {
                id: '',
                articleId: '',
                lang: 'en',
                content: ''
            }
        ]
    })

    form.content = ''
    form.EnContent = ''
    form.id = ''
    form.authorName = ''
    form.title = ''
    form.status = 'UP'
    form.upTime = ''
    form.ranking = 1
    form.image = ''
    form.officialArticleItemList = [
        {
            id: '',
            articleId: '',
            lang: 'zh',
            content: ''
        },
        {
            id: '',
            articleId: '',
            lang: 'en',
            content: ''
        }
    ]
    //手动清空数据

    //显示中文tab
    activeName.value = 'first'
    
    //打开弹窗
    showSubBtn.value = true;
    showEditor.value = true;
    formDrawerRef.value.open()
}

// 提交表单
const handleSubmit = () => {
    form.content = editorRef.value.valueHtml
    form.EnContent = editorRef_en.value.valueHtml
    //表单校验
    formRef.value.validate((valid) => {
        console.log('校验结果：', valid)
        if (!valid) return

        //loading
        formDrawerRef.value.showLoading()

        form.officialArticleItemList.forEach(item => {
            if (item.lang == 'zh') {
                item.content = form.content;
            } else if (item.lang == 'en') {
                item.content = form.EnContent;
            }
        });
        console.log('form.officialArticleItemList: ', form.officialArticleItemList)
        const fun = articleAddOrUpdate(form)

        fun.then(res => {
            toast(drawerTitle.value + "成功")
            // 修改刷新当前页，新增刷新第一页
            getData(editId.value ? false : 1)
            formDrawerRef.value.close()
        }).finally(() => {
            //close loading
            formDrawerRef.value.hideLoading()
        })
    })
}

// 编辑
const handleEdit = async (row) => {
    editId.value = row.id
    drawerTitle.value = '修改'
    let articleRes = await article_detail_api({ id: row.id })
    console.log('文章详情：', articleRes)
    resetForm(articleRes)
    articleRes.officialArticleItemList.forEach(item => {
        if (item.lang == 'zh') {
            form.content = item.content;
        } else if (item.lang == 'en') {
            form.EnContent = item.content;
        }
    })
    console.log('handle edit form: ', form)
    showSubBtn.value = true;
    // 文章图片
    showArticlePic(row);
    showEditor.value = true;
    formDrawerRef.value.open()
    //   showEditor.value = true
}
// 删除
const handleDelete = (row) => {
    searchForm.id = row.id;
    console.log('search form', searchForm)
    article_delete_api(searchForm).then(res => {
        console.log('文章删除结果：', res)
        getData();
        toast('文章删除成功')
    })
}

const showArticlePic = (row) => {
    if (row.image) {
        proofImage.value = row.image;
        fileList.value = []
        let obj = {
            url: 'data:image/jpeg;base64,' + proofImage.value
        }
        fileList.value.push(obj);
    }

}
// 详情
const handleDetail = async (row) => {
    drawerTitle.value = '详情'
    let articleRes = await article_detail_api({ id: row.id })
    console.log('文章详情：', articleRes)
    resetForm(articleRes)
    articleRes.officialArticleItemList.forEach(item => {
        if (item.lang == 'zh') {
            form.content = item.content;
        } else if (item.lang == 'en') {
            form.EnContent = item.content;
        }
    })
    showSubBtn.value = false;
    // 文章图片
    showArticlePic(row);
    showEditor.value = true;
    formDrawerRef.value.open()
    //   showEditor.value = true
}


function getFile(file, fileList) {
    console.log('get file function')
    getBase64(file.raw).then(res => {
        const params = res.split(',')
        console.log(params, 'params')
        if (params.length > 0) {
            form.image = params[1]
            // formRef.value.validate((validResult) => {
            //     console.log('表单校验结果：', validResult)
            // })
        }

    })
}

async function onExceed_file(files) {
    console.log(files)
    fileList.value = []
    const file = files[files.length - 1]
    getBase64(file).then(res => {
        const params = res.split(',')
        console.log(params, 'params')
        if (params.length > 0) {
            form.image = params[1]
            proofImage.value = params[1]
        }
        let obj = {
            name: file.name,
            url: 'data:image/jpeg;base64,' + proofImage.value
        }
        fileList.value.push(obj);
    })

}

function getBase64(file) {
    return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
            imgResult = reader.result
        }
        reader.onerror = function (error) {
            reject(error)
        }
        reader.onloadend = function () {
            resolve(imgResult)
        }
    })
}
function handleUploadRemove(file, fileList) {
    proofImage.value = '';
}
//关闭
const isClosed = () => {
    //console.log("isClosed")
    //editorRef.value.destroyEditor()
    showEditor.value = false
}



// ------------------- life function --------------

onMounted(() => {
    getData();

    console.log('form: ', form)
})

</script>

<style></style>